<?php

declare(strict_types=1);

namespace App\Model\PssLogModel;

use App\Model\BaseModel\BasePssLogModel;
use Service\AppService\IdService;
use App\Amqp\Producer\MicroServiceHyperfLogMessageProducer;
use Hyperf\Amqp\Producer;
use Service\Code\Normal;

/**
 * 添加日志写入行为
 */
class MicroServiceLog extends BasePssLogModel
{
    public $table = 'micro_service_hyperf_log';
    
    /**
     * 添加日志
     * @param array $param
     */
    public function addLog( $param = [] )
    {
        $addLog = [
            'interface_code'    => $param['interface_code'] ?? '',
            'request_url'       => $param['request_url'] ?? '',
            'request_param'     => $param['request_param'] ?? '',
            'response_code'     => $param['response_code'] ?? '',
            'response_data'     => $param['response_data'] ?? '',
            'req_used_time'     => (string)($param['req_used_time'] ?? ''),
            'cd'                => time(),
        ];
        return $this->publish($param);
        
       /*  return waiter(function() use ($param)
        {
            return $this->add([
                'id'                => IdService::instance()->getLogID(),
                'interface_code'    => $param['interface_code'] ?? '',
                'request_url'       => $param['request_url'] ?? '',
                'request_param'     => $param['request_param'] ?? '',
                'response_code'     => $param['response_code'] ?? '',
                'response_data'     => $param['response_data'] ?? '',
                'req_used_time'     => $param['req_used_time'] ?? '',
                'cd'                => time(),
            ]);
        },120); */
    }    
    
    /**
     * 发布消息日志
     */
    public function publish( array $message )
    {
        try {
            $handlerMessage = new MicroServiceHyperfLogMessageProducer($message);
            $producer = container()->get(Producer::class);
            $result = $producer->produce($handlerMessage,true);
            if( $result ) {
                return Normal::returnCode(Normal::SUC,"发布成功");
            }
            return Normal::returnCode(Normal::FAIL,"操作失败，请稍微再试[100000]");
        } catch ( \Throwable $e ) {
            return Normal::returnCode(Normal::FAIL,"操作失败，请稍微再试[{$e->getMessage()},{$e->getLine()},{$e->getFile()}]");
        }
    }
}
